/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.filter.qrcode;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import org.elsfs.cloud.common.security.filter.AbstractFormFilter;
import org.elsfs.cloud.common.security.filter.phone.sms.PhoneSmsAuthenticationToken;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.context.DelegatingSecurityContextRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

/**
 * 二维码登录
 *
 * @author zeng
 */
public class QrcodeAuthenticationFilter extends AbstractFormFilter {
  public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/qrCode";
  private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER =
      new AntPathRequestMatcher(DEFAULT_FILTER_PROCESSES_URI, "POST");

  public static final String SPRING_SECURITY_FORM_PHONE_KEY = "phone";
  public static final String SPRING_SECURITY_FORM_SMS_KEY = "sms";
  private String phoneParameter = SPRING_SECURITY_FORM_PHONE_KEY;
  private String smsParameter = SPRING_SECURITY_FORM_SMS_KEY;
  private boolean postOnly = true;

  /** 构造器 */
  public QrcodeAuthenticationFilter() {
    super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    // https://github.com/spring-projects/spring-security/issues/13225
    setSecurityContextRepository(
        new DelegatingSecurityContextRepository(
            new RequestAttributeSecurityContextRepository(),
            new HttpSessionSecurityContextRepository()));
  }

  @Override
  public Authentication attemptAuthentication(
      HttpServletRequest request, HttpServletResponse response)
      throws AuthenticationException, IOException, ServletException {
    if (this.postOnly && !request.getMethod().equals("POST")) {
      throw new AuthenticationServiceException(
          "Authentication method not supported: " + request.getMethod());
    }
    String phone;
    String sms;
    if (isJson(request)) {
      try {
        var read = objectMapper.reader().readValue(request.getInputStream(), Map.class);
        phone = read.get(getPhoneParameter()) instanceof String ph ? ph : "";
        sms = read.get(getSmsParameter()) instanceof String p ? p : "";
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      phone = obtainPhone(request);
      sms = obtainSms(request);
    }
    phone = (phone != null) ? phone.trim() : "";
    sms = (sms != null) ? sms : "";
    PhoneSmsAuthenticationToken authRequest =
        PhoneSmsAuthenticationToken.unauthenticated(phone, sms);

    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);
    return getAuthenticationManager().authenticate(authRequest);
  }

  @Nullable
  protected String obtainSms(HttpServletRequest request) {
    return request.getParameter(this.smsParameter);
  }

  @Nullable
  protected String obtainPhone(HttpServletRequest request) {
    return request.getParameter(this.phoneParameter);
  }

  protected void setDetails(HttpServletRequest request, PhoneSmsAuthenticationToken authRequest) {
    authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
  }

  public void setPhoneParameter(String phoneParameter) {
    Assert.hasText(phoneParameter, "Username parameter must not be empty or null");
    this.phoneParameter = phoneParameter;
  }

  public void setSmsParameter(String smsParameter) {
    Assert.hasText(smsParameter, "Password parameter must not be empty or null");
    this.smsParameter = smsParameter;
  }

  public void setPostOnly(boolean postOnly) {
    this.postOnly = postOnly;
  }

  public final String getPhoneParameter() {
    return this.phoneParameter;
  }

  public final String getSmsParameter() {
    return this.smsParameter;
  }
}
